package elijah.base.net;


import android.content.Context;

import com.lxj.xpopup.XPopup;

import elijah.base.AppBase;
import elijah.base.excetion.ExceptionHandler;
import elijah.base.result.IResult;
import elijah.base.utils.Toasts;

/**
 * @param <T>
 */
public abstract class BaseResult<T> extends BaseProgressObserver<T> {
    private boolean silence = false;

    public BaseResult() {
        super();
    }


    public BaseResult(Context context) {
        super(context);
    }

    public BaseResult(Context context, String content) {
        super(context, content);
    }

    public BaseResult(Context context, boolean showDialog) {
        super(context, showDialog);
    }


    public BaseResult(Context context, boolean showDialog, String content) {
        super(context, showDialog, true, content);
    }

    public BaseResult(Context context, boolean showDialog, String content, boolean silence) {
        super(context, showDialog, true, content);
        this.silence = silence;
    }

    public BaseResult(Context context, boolean showDialog, boolean fillWindow) {
        super(context, showDialog, fillWindow);
    }

    @Override
    public void customerDialog(XPopup.Builder dialogBuilder) {
        super.customerDialog(dialogBuilder);
    }

    @Override
    public void onSuccess(T t) {
        super.onSuccess(t);
        if (!(t instanceof IResult)) {
            result(t);
            return;
        }
        IResult data = (IResult) t;
        AppBase.setTimeStamp(data.getTime());
        if (!data.isResult()) {
            if (silence) {
                return;
            }
            Toasts.showErrorToast(data.getError());
            return;
        }
        result(t);

    }

    private void result(T t) {
        try {
            success(t);
        } catch (Exception e) {
            e.printStackTrace();
            Toasts.showErrorToastAsync("数据解析异常: " + e.getMessage());

        }
    }

    @Override
    public void error(final Throwable e) {
        if (silence) {
            return;
        }
        e.printStackTrace();
        Toasts.showErrorToastAsync(ExceptionHandler.handle(e).toString());

    }


    public abstract void success(T t) throws Exception;

}
